import { Injectable } from '@angular/core';
import {
    CanActivate,
    CanActivateChild,
    Router,
    ActivatedRouteSnapshot,
    RouterStateSnapshot
} from '@angular/router';

@Injectable({
    providedIn: 'root'
})

export class LoginGuard implements CanActivate, CanActivateChild {

    constructor(private router: Router) { }

    canActivate(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        console.log('canActivate守卫成功');
        const token = sessionStorage.getItem('token');
        if (!token) {
            this.router.navigate(['/login']);
        }
        return !!token;
    }

    canActivateChild(
        route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): boolean {
        console.log('canActivateChild守卫成功');
        return this.canActivate(route, state);
    }
}
